package repository

import (
	"fmt"
	"slapp3/backend/application/domain"
	"slapp3/backend/application/utils"
	"slapp3/backend/config"

	"github.com/glebarez/sqlite"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// Data .
type Data struct {
	db   *gorm.DB
	log  *zap.Logger
	conf *config.Config
}

// NewData .
func NewData(c *config.Config, logger *zap.Logger) (*Data, func(), error) {
	_log := &utils.CustomGORMLogger{
		Clog:     logger,
		TraceSql: true,
	}
	fmt.Printf("Connecting to database: %s\n", c.Database.Dsn)
	db, err := gorm.Open(sqlite.Open(c.Database.Dsn), &gorm.Config{
		Logger: _log,
	})
	if err != nil {
		return nil, nil, err
	}

	data := &Data{
		db:   db,
		log:  logger,
		conf: c,
	}

	if err := InitDBData(data); err != nil {
		return nil, nil, fmt.Errorf("failed to initialize database: %w", err)
	}

	closeFunc := func() {
		sqlDB, err := db.DB()
		if err != nil {
			data.log.Error("Failed to get SQL DB instance", zap.Error(err))
			return
		}
		sqlDB.Close()
	}

	return data, closeFunc, nil
}

func InitDBData(data *Data) error {
	if err := data.db.AutoMigrate(&domain.Profile{}); err != nil {
		return fmt.Errorf("failed to migrate database: %w", err)
	}
	data.log.Info("Database migration completed successfully")
	return nil
}
